/**
 * @fileOverview 此脚本用于将 api 文件夹打包成ZIP文件。
 * @author [mac-xiang]
 */
import archiver from "archiver";
import * as fs from "fs";
import * as path from "path";

export function zip(targetFolder: string, outPath = "api.zip") {
  return new Promise<string>((resolve, reject) => {
    const
      op = path.resolve(outPath),
      output = fs.createWriteStream(op),
      archive = archiver("zip", { zlib: { level: 9 } });
    output.on('close', () => {
      resolve(op);
    });
    archive.on('error', (err) => { reject(err); });
    fs.readdirSync(targetFolder).forEach(fn => {
      const file = path.join(targetFolder, fn);
      if (fs.statSync(file).isDirectory()) {
        if (fn == "src") {
          archive.directory(file, path.relative(targetFolder, file));
        }
      } else { archive.file(file, { name: path.relative(targetFolder, file) }); }
    });
    // 将归档数据写入输出文件
    archive.pipe(output);
    // 开始打包
    archive.finalize();
  });
}
export default zip;
